package com.example.service.impl;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.entity.dto.CenterConfigDto;
import com.example.entity.dto.CenterConfigSelectDto;
import com.example.entity.dto.CenterWorkLeaderDto;
import com.example.entity.vo.CenterConfigInfoVo;
import com.example.entity.vo.CenterConfigResultVo;
import com.example.entity.vo.CenterWorkLeaderInfoVo;
import com.example.entity.yifei.CallCenterConfiguration;
import com.example.entity.yifei.CallCenterWorkLeader;
import com.example.exception.CustomException;
import com.example.mapper.CallCenterConfigMapper;
import com.example.mapper.CallCenterLeaderMapper;
import com.example.service.CallCenterConfigService;
import com.example.untils.SecurityUtils;
import com.example.untils.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Joiner;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class CallCenterConfigServiceImpl implements CallCenterConfigService {

    @Autowired
    private CallCenterConfigMapper mapper;

    @Autowired
    private CallCenterLeaderMapper leaderMapper;

    @Override
    @DSTransactional
    public void add(CenterConfigDto dto) {
//        if (dto.getDistrictId() != null && !dto.getDistrictId().isEmpty()
//                && !"district".equals(dto.getDecisionType()))
//            throw new CustomException("500","片区id仅在绑定类型为'district'时生效");
        isContainsDup(dto);
        String nowTime = StringUtils.ifEmptySet(dto.getCreatorTime(), LocalDate.now().toString());
        String creator = SecurityUtils.getLoginUser().getUsername();
        dto.setCreatorTime(nowTime)
                .setCreator(creator);
        CallCenterConfiguration vo = new CallCenterConfiguration();
        BeanUtils.copyProperties(dto, vo);
        vo.setUuid(null);
        try{
            mapper.insert(vo);
        }catch (DataIntegrityViolationException e){
            throw new CustomException("500","班别加工作中心已存在");
        }
        //判断是否有故障相关人员信息
        if (dto.getWorkLeaderList() != null && !dto.getWorkLeaderList().isEmpty()) {
            for (CenterWorkLeaderDto leaderDto : dto.getWorkLeaderList()) {
                String lNowTime = StringUtils.ifEmptySet(leaderDto.getCreatorTime(), nowTime);
                String lCreator = StringUtils.ifEmptySet(leaderDto.getCreator(),creator);
                leaderDto.setParentId(vo.getUuid()).setCreatorTime(lNowTime)
                        .setCreator(lCreator);
                CallCenterWorkLeader leader = new CallCenterWorkLeader();
                BeanUtils.copyProperties(leaderDto, leader);
                leader.setUuid(null);
                if (!(leaderDto.getWorkLeader() == null || leaderDto.getWorkLeader().isEmpty()))
                    leader.setWorkLeader(Joiner.on(",").join(leaderDto.getWorkLeader()));
                leaderMapper.insert(leader);
            }
        }
    }

    @Override
    @DSTransactional
    public void update(CenterConfigDto dto) {
        if (dto.getUuid() == null || mapper.selectById(dto.getUuid()) == null) return;
        CenterConfigInfoVo one = mapper.one(dto.getUuid());
        AtomicInteger sameNum=new AtomicInteger(0);
        List<String> newList = new ArrayList<>(Arrays.asList(dto.getWorkbenchId().trim().split(",")));
        List<String> oriList = new ArrayList<>(Arrays.asList(one.getWorkbenchId().trim().split(",")));
        oriList.forEach(item->{
            if (newList.contains(item)) sameNum.addAndGet(1);
        });
        if (!dto.getDuty().equals(one.getDuty()) || !dto.getFaultType().equals(one.getFaultType()) || sameNum.get()!=newList.size())
            isContainsDup(dto);
        String nowTime = LocalDate.now().toString();
        String user = SecurityUtils.getLoginUser().getUsername();
        CallCenterConfiguration vo = new CallCenterConfiguration();
        BeanUtils.copyProperties(dto, vo);
        vo.setModifierTime(nowTime)
                .setModifier(user);
        mapper.updateById(vo);
        //判断是否有修改故障相关人员信息
        if (dto.getWorkLeaderList() != null && !dto.getWorkLeaderList().isEmpty()) {
            leaderMapper.delete(new LambdaQueryWrapper<CallCenterWorkLeader>().eq(CallCenterWorkLeader::getParentId, vo.getUuid()));
            for (CenterWorkLeaderDto leaderDto : dto.getWorkLeaderList()) {
                CallCenterWorkLeader leader = new CallCenterWorkLeader();
                BeanUtils.copyProperties(leaderDto, leader);
                leader.setModifierTime(nowTime)
                        .setModifier(user)
                        .setCreatorTime(nowTime)
                        .setCreator(user)
                        .setParentId(vo.getUuid());
                if (!(leaderDto.getWorkLeader() == null || leaderDto.getWorkLeader().isEmpty()))
                    leader.setWorkLeader(Joiner.on(",").join(leaderDto.getWorkLeader()));
                leaderMapper.insert(leader);
            }
        }
    }

    @Override
    public CenterConfigResultVo list(CenterConfigSelectDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<CenterConfigInfoVo> list = mapper.list();
        PageInfo<CenterConfigInfoVo> pageInfo = new PageInfo<>(list);
        //所有机台id
        HashSet<String> workbenchIds= new HashSet<>();
        //封装所有对应的相关人员
        List<CenterConfigInfoVo> results = new ArrayList<>();
        for (CenterConfigInfoVo result : pageInfo.getList()) {
            if (!StringUtils.isEmpty(result.getWorkbenchId())){
                List<String> ids = new ArrayList<>(Arrays.asList(result.getWorkbenchId().split(",")))
                        .stream().map(String::trim).collect(Collectors.toList());
                result.setWorkbenchIds(ids);
                workbenchIds.addAll(result.getWorkbenchIds());
            }
            results.add(one(result.getUuid()));
        }
        //查询所有机台信息
        if (!workbenchIds.isEmpty()){
            Map<String, String> workbanchs = mapper.selectWorkbench(new ArrayList<>(workbenchIds)).stream()
                    .collect(Collectors.toMap(CenterConfigInfoVo::getWorkbenchId, CenterConfigInfoVo::getWorkbenchName));
            results.forEach(item->{
                if (!StringUtils.isEmpty(item.getWorkbenchId())){
                    List<Map<String,String>> workbanchInfo= new ArrayList<>();
                    for (String workbenchId : item.getWorkbenchIds()) {
                        Map<String,String> map=new HashMap<>();
                        map.put("workbenchId",workbenchId);
                        map.put("workbenchName", workbanchs.getOrDefault(workbenchId, null));
                        workbanchInfo.add(map);
                    }
                    item.setWorkbenchInfo(workbanchInfo);
                }
            });
        }
        return new CenterConfigResultVo((int) pageInfo.getTotal(), results);
    }

    @Override
    public CenterConfigInfoVo one(Integer id) {
        CenterConfigInfoVo vo = mapper.one(id);
        if (!StringUtils.isEmpty(vo.getWorkbenchId())){
            List<String> ids = new ArrayList<>(Arrays.asList(vo.getWorkbenchId().split(",")))
                    .stream().map(String::trim).collect(Collectors.toList());
            vo.setWorkbenchIds(ids);
            Map<String, String> workbanchs = mapper.selectWorkbench(ids).stream()
                    .collect(Collectors.toMap(CenterConfigInfoVo::getWorkbenchId, CenterConfigInfoVo::getWorkbenchName));
            if (!workbanchs.isEmpty()) {
                List<Map<String,String>> workbanchInfo= new ArrayList<>();
                for (String workbenchId : vo.getWorkbenchIds()) {
                    Map<String,String> map=new HashMap<>();
                    map.put("workbenchId",workbenchId);
                    map.put("workbenchName", workbanchs.getOrDefault(workbenchId, null));
                    workbanchInfo.add(map);
                }
                vo.setWorkbenchInfo(workbanchInfo);
            }
        }
        //查询所有故障负责人信息
        List<CallCenterWorkLeader> list = leaderMapper.list(id);
        if (list == null || list.isEmpty()) return vo;
        return vo.setWorkLeader(
                list.stream().map(item -> {
                    CenterWorkLeaderInfoVo infoVo = new CenterWorkLeaderInfoVo();
                    BeanUtils.copyProperties(item, infoVo);
                    return infoVo.setWorkLeader(item.getWorkLeader() == null ?
                            new ArrayList<>():new ArrayList<>(Arrays.asList(item.getWorkLeader().split(","))));
                }).collect(Collectors.toList())
        );
    }

    /**
     * 判断当前传入的班别+故障类型+机器号是否已存在
     * @param dto
     */
    private void isContainsDup(CenterConfigDto dto){
        if(!StringUtils.isEmpty(dto.getWorkbenchId())){
            //机台不为null,判断是否有机台重合
            //获取要加入的配置的所有机台信息
            HashSet<String> nowCombos= new HashSet<>();
            new ArrayList<>(Arrays.asList(dto.getWorkbenchId().split(","))).forEach(item->{
                        nowCombos.add(item.trim());
                    });
            List<CallCenterConfiguration> configs = mapper.likeBanchIds(dto.getFaultType(),dto.getDuty());
            //获取所有机台
            HashSet<String> allCombos= new HashSet<>();
            for(CallCenterConfiguration config : configs){
                if (!Objects.equals(config.getUuid(), dto.getUuid())){
                    new ArrayList<>(Arrays.asList(config.getWorkbenchId().split(","))).forEach(item->{
                                allCombos.add(item.trim());
                            });
                }
            }
            if (CollectionUtils.containsAny(allCombos,nowCombos))
                throw new CustomException("500","当前班别+故障类型+机器号已存在");
        }
    }
}
